import os

from Transcode import Transcode
from WBparse import WBparse
from PanlexDict import PanlexDict



class lextract:
    """This class is the interface to lextract."""
    #___________________________________________________________________________

    def __init__(self, debug=False):
        self.clear()
        self.dict = PanlexDict()
        self._debug = debug


    #___________________________________________________________________________

    def clear(self):
        self._source = ""
        self._tmpdir = "/tmp/"
        self._tmpfilebase = "lextract"
        self._tmpfileid = 0

    #___________________________________________________________________________

    def initTempFile(self):
        """Create a temp file, and return the location"""
        while True:
            tmpfile = self._tmpdir + self._tmpfilebase + str(self._tmpfileid)
            if not os.path.exists(tmpfile):
                open(tmpfile, 'a').close()
                break
            else:
                self._tmpfileid += 1
        return tmpfile

    #___________________________________________________________________________

    def transcode(self, infile):
        """Transcode `infile' to utf-8, saving the results in the temp file returned by the function"""
        self._source = infile
        tmpfile = self.initTempFile()
        Transcode(infile,tmpfile)
        return tmpfile

    #___________________________________________________________________________
    

    def WBparsefile(self, infile, outfile, sourceLang, targetLangList,multipleTarget=False):
        """Transcode `infile' to utf-8, and parse the output as a WB file"""
        self._source = infile
        tmpfile = self.initTempFile()
        Transcode(infile,tmpfile)
        WBparse(tmpfile,outfile,sourceLang,targetLangList,multipleTarget)
        os.remove(tmpfile)

    #___________________________________________________________________________
    


class lextracterror(Exception):
    pass
